package com.isaacwaller.digg;

import java.io.IOException;
import java.net.URISyntaxException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.database.DataSetObserver;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.TextView;

public class DiggResponseListAdapter implements ListAdapter {
	static String TAG = "DiggResponseLA";
	
	JSONArray response;
	Context c;
	String from;
	
	
	DiggResponseListAdapter(Context c,String url, String rootElement, String from) throws ClientProtocolException, URISyntaxException, IOException, JSONException {
		this.c = c;
		this.from = from;
		JSONObject jsonresponse = DiggInterface.makeRequest(url);
		Log.v(TAG,"JSON Response: "+jsonresponse.toString());
		Log.i(TAG, "Response completed. Timestamp:"+jsonresponse.getInt("timestamp"));
		response = jsonresponse.getJSONArray(rootElement);
	}
	
	public boolean areAllItemsEnabled() {
		return true;
	}
	public boolean isEnabled(int arg0) {
		return true;
	}
	public int getCount() {
		return response.length();
	}
	public Object getItem(int arg0) {
		try {
			return response.getJSONObject(arg0);
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}
	public long getItemId(int arg0) {
		return 0;
	}
	public int getItemViewType(int arg0) {
		return 0;
	}
	public View getView(int arg0, View arg1, ViewGroup arg2) {
		TextView textView = (TextView)View.inflate(c, R.layout.singleline, null);
		try {
			textView.setText(response.getJSONObject(arg0).getString(from));
		} catch (JSONException e) {
			textView.setText("error");
			e.printStackTrace();
		}
		return textView;
	}
	public int getViewTypeCount() {
		return 1;
	}
	public boolean hasStableIds() {
		return false;
	}
	public boolean isEmpty() {
		return response.length()==0;
	}
	public void registerDataSetObserver(DataSetObserver arg0) {
	}
	public void unregisterDataSetObserver(DataSetObserver arg0) {
	}
}
